package com.frame.auth.resource.security;

import com.frame.auth.resource.security.common.SecurityRequest;
import com.frame.auth.resource.security.config.AuthBearerTokenExtractor;
import com.frame.auth.resource.security.config.GlobalRemoteTokenServices;
import com.frame.auth.resource.security.config.PermitAllUrlProperties;
import com.frame.auth.resource.security.exception.AuthExceptionEntryPoint;
import com.frame.auth.resource.security.handler.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * oauth2资源服务器配置
 *
 * @auther zhangwj
 * @date 2021/3/10 下午8:18
 */
@Configuration
@EnableResourceServer
@ConditionalOnWebApplication
@PropertySource("classpath:security-config.properties")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ConditionalOnClass(AuthBearerTokenExtractor.class)
@EnableConfigurationProperties(SecurityRequest.class)
@AutoConfigureAfter(PermitAllUrlProperties.class)
public class AuthResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Value(value = "${security.oauth2.client.client-id}")
    private String clientId;

    @Value(value = "${security.oauth2.client.client-secret}")
    private String secret;

    @Value(value = "${security.oauth2.authorization.check-token-access}")
    private String checkTokenEndpointUrl;

    @Value(value = "${security.oauth2.resource.id}")
    private String resourceId;

    private String[] excludeUrl = {"/message/getCode/*"};

    @Resource
    private SecurityRequest securityRequest;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private PermitAllUrlProperties permitAllUrlProperties;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        List<String> ignoreUrls = permitAllUrlProperties.getIgnoreUrls();
        ignoreUrls.addAll(Arrays.asList(excludeUrl));
        String[] urls = new String[ignoreUrls.size()];
        urls = ignoreUrls.toArray(urls);
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .httpBasic().authenticationEntryPoint(new GoAuthenticationEntryPoint())
                .and().authorizeRequests().antMatchers(urls).permitAll()
                .antMatchers("/**").authenticated().anyRequest().permitAll()
                .and().formLogin()
                .successHandler(new GoAuthenticationSuccessHandler())
                .failureHandler(new GoAuthenticationFailureHandler()).permitAll().and().logout().logoutUrl("/login/out")
                .logoutSuccessHandler(new GoLogoutSuccessHandler());
        http.exceptionHandling()
                .accessDeniedHandler(new GoAccessDeniedHandler());
    }

    @Bean
    public GlobalRemoteTokenServices tokenService() {
        GlobalRemoteTokenServices tokenService = new GlobalRemoteTokenServices();
        tokenService.setRestTemplate(restTemplate);
        tokenService.setClientId(clientId);
        tokenService.setClientSecret(secret);
        tokenService.setCheckTokenEndpointUrl(checkTokenEndpointUrl);
        return tokenService;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(resourceId);
        resources.tokenServices(tokenService());
        resources.authenticationEntryPoint(new AuthExceptionEntryPoint());
        resources.tokenExtractor(authBearerTokenExtractor());
    }

    @Bean
    @ConditionalOnMissingBean(AuthBearerTokenExtractor.class)
    @ConditionalOnProperty(prefix = "security", value = "enabled", havingValue = "true")
    public AuthBearerTokenExtractor authBearerTokenExtractor() {
        return new AuthBearerTokenExtractor(securityRequest);
    }
}

